//
//  UserAccount.swift
//  01MicroBlog
//
//  Created by Apple on 15/7/30.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    
 /// 标记用户是否登录
    class var userLogon: Bool {
        // 从沙盒中读取，是否存在账户
        return (sharedAccount != nil) as Bool
    }

    // MARK: - 定义全局账户属性
    private static var userAccount:UserAccount?
    
    // 测试缓存图片的长度
    private var dataLength = 0
    
    // 定义类属性
    class var sharedAccount:UserAccount? {
        // 1.如果账户为空，则从沙盒中解档，获取账户
            if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountpath) as? UserAccount
            }
            
            // 2.判断日期
            // 测试过期日期
            //        userAccount!.expiresDate = NSDate(timeIntervalSinceNow: -100)
            if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            // 能来到这表示账号已经过期，需要清空账号记录
            userAccount = nil
        }
        return userAccount
    }
    
    // 令牌数据
    var access_token:String?
    
    // 过期时间数值
    var expires_in:NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期日期
    var expiresDate: NSDate?

    // 用户ID
    var uid:String?
    
    // 用户头像地址 180*180像素
    var avatar_large:String?
    // 友好显示
    var name:String?
    
    // 字典的构造方法
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        // 设置全局的用户信息
        UserAccount.userAccount = self
    }
    
    // MARK: - 归档、解档
    // 注明哪些属性需要归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    // 注明哪些属性需要解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
 /// 保存文档文件的路径
    static private let accountpath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("account.plist")
    
    // MARK: - 保存用户账号
    // 对象方法访问属性时，需要加上类名
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountpath)
    }
    
    // MARK: - 加载用户信息
    /// 加载用户信息 － 调用方法，异步获取用户附加信息，保存当前用户信息
    func loadUserInfo(finished: (error: NSError?) -> ()) {
        NetworkTools.sharedNetworkTools.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil {
                // 提示：error一定要传递！
                finished(error: error)
                return
            }
            
            // 设置用户信息
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccount()
            
            print("name----\(self.name)")
            print("avatar_large---\(self.avatar_large)")
            
            // 完成回调
            finished(error: nil)
        }
    }

    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    // 对象描述信息
    override var description: String {
        let properties = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
}
